package com.atom.module.lib.opengles.texture

import android.opengl.GLES30
import com.atom.module.lib.opengles.draw.GlBindable
import com.atom.module.lib.opengles.draw.use
import com.atom.module.lib.opengles.util.ShaderUtils
import kotlin.jvm.JvmOverloads

class GlFramebuffer(id: Int? = null) : GlBindable {

    val id: Int = id ?: run {
        val array = IntArray(1)
        GLES30.glGenFramebuffers(1, array, 0)
        ShaderUtils.checkGLError("glGenFramebuffers")
        if (array[0] == 0) {
            throw RuntimeException("glGenFramebuffers  == 0")
        }
        array[0]
    }

    @JvmOverloads
    fun attach(texture: GlTexture, attachment: Int = GLES30.GL_COLOR_ATTACHMENT0) {
        use {
            GLES30.glFramebufferTexture2D(
                GLES30.GL_FRAMEBUFFER,
                attachment, texture.target, texture.id, 0
            )
            val status = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER)
            if (status != GLES30.GL_FRAMEBUFFER_COMPLETE) {
                throw RuntimeException("Invalid framebuffer generation. Error:$status")
            }
        }
    }

    override fun bind() {
        GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, id)
    }

    override fun unbind() {
        GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
    }

    fun release() {
        GLES30.glDeleteFramebuffers(1, intArrayOf(id), 0)
    }
}